package cn.ges.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 简单的封装fastJson的json转换工具类<br>
 * 仅是为了调用更加方便
 *
 * @author gespent@163.com
 * @date 2018/11/30
 */
public class JsonUtil {
    public static String objectToJson(Object obj) {
        return JSON.toJSONString(obj);
    }

    public static <T> T cast2SameFiled(Object o, Class<T> tClass) {
        final String s = objectToJson(o);
        return JsonUtil.jsonToObject(s, tClass);
    }

    public static <T> T jsonToObject(String json, Class<T> clazz) {
        T t;
        try {
            t = JSON.parseObject(json, clazz);
        } catch (Exception e) {
            return null;
        }
        return t;
    }

    public static <T> ArrayList<T> jsonArrayList2ArrayList(List<T> list) {
        if (list.isEmpty()) {
            return new ArrayList<T>(0);
        }

        if (list instanceof JSONArray) {
            final ArrayList<T> ts = new ArrayList<>(list.size());
            final Class<?> aClass = list.get(0).getClass();
            final JSONArray list1 = (JSONArray) list;
            if (aClass.getName().equals(JSONObject.class.getName())) {
                for (Object o : list1) {
                    if (o instanceof JSONObject) {
                        final JSONObject o1 = (JSONObject) o;
                        final Object parse = JSON.parseObject(o1.toJSONString());
                        ts.add((T) parse);
                    }
                }
                return ts;
            } else {
                return (ArrayList<T>) list1.toJavaList(aClass);
            }

        }
        if (list instanceof ArrayList) {
            return (ArrayList<T>) list;
        }
        return new ArrayList<T>(0);
    }

}
